package com.gestionabsences.servlets;

import com.gestionabsences.beans.MapMatters;
import com.gestionabsences.beans.ResultRequest;
import com.gestionabsences.beans.WebUser;
import com.gestionabsences.config.DAOFactory;
import com.gestionabsences.database.ToolsRequest;
import com.gestionabsences.form.FormTeacher;
import com.gestionabsences.form.FormTeacherReport;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author matt
 */
public class HomeTeacher extends HttpServlet {

    public static final String ATT_PAGE = "requestedPage";
    public static final String VUE_HOME = "/WEB-INF/Inc/enseignant/home.jsp";
    public static final String VUE_QUERY = "gui_query.jsp";
    public static final String VUE_REPORT_ABSENCES = "gui_report_absences.jsp";
    public static final String VUE_READ_ME = "readme.jsp";
    
    private static final String ATT_DAO_FACTORY = "daofactory";
    public static final String ATT_SESSION_WEBUSER = "sessionWebuser";
    public static final String ATT_SESSION_LISTE_MATIERE = "listeMatieres";
    
    public static final String ATT_FORM_QUERY = "form";
    public static final String ATT_RESULT_QUERY_ABSENCES = "resultatQueryAbsences";
    
    public static final String ATT_FORM_GET_MATIERE = "formGetMatiere";
    public static final String ATT_RESULT_QUERY_LIST_SEANCES = "resultatQueryListSeances";
    
    public static final String ATT_FORM_GET_SEANCE = "formGetSeance";
    public static final String ATT_RESULT_QUERY_LIST_STUDENTS = "resultatQueryListStudents";
    
    public static final String ATT_FORM_GET_ABSENTS = "formGetAbsents";
    public static final String ATT_RESULT_INSERTION = "resultatInsertion";
    
    
    private DAOFactory dao;
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	HttpSession session = request.getSession();
	
	WebUser user = (WebUser) session.getAttribute( ATT_SESSION_WEBUSER );
	
        MapMatters listMatieres = (MapMatters) session.getAttribute( ATT_SESSION_LISTE_MATIERE );
	if(listMatieres == null) {
	    listMatieres = creerListeMatieres( user.getPrimaryKey() );
	    session.setAttribute(ATT_SESSION_LISTE_MATIERE, listMatieres);
	}
	
	String page = request.getParameter( "page" );
	
	if (page != null && listMatieres != null) {
	    if (page.compareTo("report") == 0) {
		request.setAttribute(ATT_PAGE, VUE_REPORT_ABSENCES);
	    } else if (page.compareTo("query") == 0) {
		request.setAttribute(ATT_PAGE, VUE_QUERY);
	    } else {
		request.setAttribute(ATT_PAGE, VUE_READ_ME);
	    }
	} else {
	    request.setAttribute(ATT_PAGE, VUE_READ_ME);
	}
	
	this.getServletContext().getRequestDispatcher( VUE_HOME ).forward( request, response );
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	HttpSession session = request.getSession();
	
	WebUser user = (WebUser) session.getAttribute( ATT_SESSION_WEBUSER );
	
        MapMatters listMatieres = (MapMatters) session.getAttribute( ATT_SESSION_LISTE_MATIERE );
	if(listMatieres == null) {
	    listMatieres = creerListeMatieres( user.getPrimaryKey() );
	    session.setAttribute(ATT_SESSION_LISTE_MATIERE, listMatieres);
	}
	
	String page = request.getParameter( "page" );
	
	if (page != null && listMatieres != null) {
	    if (page.compareTo("report") == 0) {
		request.setAttribute(ATT_PAGE, VUE_REPORT_ABSENCES);
		
		System.out.println(request);
		
		if( request.getParameter(FormTeacherReport.CHAMP_MATIERE ) != null) {		    
		    FormTeacherReport formListSeance = new FormTeacherReport(dao, listMatieres, user.getPrimaryKey());
		    ResultRequest resReqListSeances = formListSeance.recuperationListeSeances(request);
		    request.setAttribute(ATT_FORM_GET_MATIERE, formListSeance);
		    
		    if (formListSeance.getErreurs().isEmpty()) {
			if (resReqListSeances != null) {
			    request.setAttribute(ATT_RESULT_QUERY_LIST_SEANCES, resReqListSeances);
			}
		    }
		    
		} else if ( request.getParameter(FormTeacherReport.CHAMP_MATIERE_SPECIFIE ) != null && request.getParameter(FormTeacherReport.CHAMP_SEANCE_SPECIFIE) == null) {
		    FormTeacherReport formListStudents = new FormTeacherReport(dao, listMatieres, user.getPrimaryKey());
		    ResultRequest resReqListStudents = formListStudents.recuperationListeEtudiants(request);
		    request.setAttribute(ATT_FORM_GET_SEANCE, formListStudents);
			    
		    if (formListStudents.getErreurs().isEmpty()) {
			if (resReqListStudents != null) {
			    request.setAttribute(ATT_RESULT_QUERY_LIST_STUDENTS, resReqListStudents);
			}
		    }
		    
		} else if ( request.getParameter(FormTeacherReport.CHAMP_SEANCE_SPECIFIE ) != null) {
		    FormTeacherReport formAddAbsents = new FormTeacherReport(dao, listMatieres, user.getPrimaryKey());
		    boolean succesInsertion = formAddAbsents.checkAsAbsent(request);
		    request.setAttribute(ATT_FORM_GET_ABSENTS, formAddAbsents);
		    
		    if ( formAddAbsents.getErreurs().isEmpty() ) {
			request.setAttribute(ATT_RESULT_INSERTION, formAddAbsents.getResultatInsertion());
		    }
		}		
	    } else if (page.compareTo("query") == 0) {
		request.setAttribute(ATT_PAGE, VUE_QUERY);

		FormTeacher form = new FormTeacher(dao, listMatieres, user.getPrimaryKey());
		ResultRequest resReq = form.creationResultat(request);

		request.setAttribute(ATT_FORM_QUERY, form);

		if (form.getErreurs().isEmpty()) {
		    if (resReq != null) {
			request.setAttribute(ATT_RESULT_QUERY_ABSENCES, resReq);
		    }
		}
	    }

	} else {
	    request.setAttribute(ATT_PAGE, VUE_READ_ME);
	}

	this.getServletContext().getRequestDispatcher(VUE_HOME).forward(request, response);
    }

    private MapMatters creerListeMatieres(String immatriculation)
    {
	Connection connexion = null;
	MapMatters listeMatieres = new MapMatters();
	
	String SQL_SELECT_LIST_MATIERES = "SELECT CAST(id_matiere AS VARCHAR(10)) id_matiere, matiere FROM getListMatieresEnseignant(?);";
	
	try {
	    connexion = dao.getConnection();
	    
	    PreparedStatement preparedStatement = null;
	    ResultSet resultSet = null;
	
	    try {
		preparedStatement = ToolsRequest.prepareRequest( connexion, SQL_SELECT_LIST_MATIERES, false, immatriculation);
		System.out.println( preparedStatement.toString() );
		resultSet = preparedStatement.executeQuery();
		
		String id_matiere;
		String mat;
		while ( resultSet.next() ) {
		    id_matiere = resultSet.getString( "id_matiere" );
		    mat = resultSet.getString( "matiere" );
		    System.out.println(id_matiere + " " + mat);
		    
		    listeMatieres.put( id_matiere, mat );
		}		
	    } catch(SQLException e) {}
	    finally {
		ToolsRequest.close(preparedStatement, resultSet);
	    }
	    
	} catch (SQLException e) {}
	finally {
	    ToolsRequest.close(connexion);		
	}
	
	return listeMatieres;
    }
    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
	return "Servlet de la  page d'accueil des enseignants.";
    }// </editor-fold>
    
    @Override
    public void init() throws ServletException {
	dao = (DAOFactory) getServletContext().getAttribute(ATT_DAO_FACTORY);
    }
}
